package com.csdig.html.controller;

import com.csdig.cms.model.CmsUser;
import com.csdig.cms.web.AdminContextInterceptor;
import com.csdig.html.model.ForumPost;
import com.csdig.html.service.ForumPostService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wei_jc
 * @since 1.0.0
 */
@Controller
@RequestMapping(value = "/forum_post")
public class ForumPostController {
    @Autowired
    private ForumPostService forumPostService;

    @RequestMapping(value = "/save")
    @ResponseBody
    public void save(HttpServletRequest request, ForumPost vo) throws Exception {
        CmsUser user = (CmsUser) request.getSession().getAttribute(AdminContextInterceptor.SESSION_USER_INFO);
        vo.setUser(user);
        forumPostService.saveForumPost(vo);
    }

    @RequestMapping(value = "/go")
    public String goForumPost() {
        return "forum_post";
    }

    @RequestMapping(value = "list")
    @ResponseBody
    public void list(HttpServletResponse response) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        List<ForumPost> list = forumPostService.listAll();
        result.put("total", list.size());
        result.put("rows", list);

        response.setContentType("application/json;charset=UTF-8");
        JSONObject json = JSONObject.fromObject(result);
        response.getWriter().write(json.toString());
    }

    @RequestMapping(value = "/look")
    public String look(HttpServletRequest request, int postId) throws Exception {
        ForumPost result = forumPostService.getForumPost(postId);
        request.setAttribute("forumPost", result);
        return "forum_post_look";
    }
}
